package com.qfedu.usermybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Objects;

/**
 * @auther asus
 * @date 2022/4/24 16:18
 */
public class MyBatisUtil {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得连接（从TL中获得当前线程SqlSession）
    private static SqlSession openSession() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (Objects.isNull(sqlSession)) {
            sqlSession = factory.openSession();
            THREAD_LOCAL.set(sqlSession);
        }
        return sqlSession;
    }

    //关闭释放连接
    private static void closeSession() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        sqlSession.close();
        THREAD_LOCAL.remove();
    }

    //提交事务
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSession();
    }

    //回滚事务
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }

    //获得接口实现类对象
    public static <T extends Object>T getMapper(Class<T> tClass){
        SqlSession sqlSession = openSession();
        T mapper = sqlSession.getMapper(tClass);
        return mapper;
    }
}
